package com.jy.modules.cims.settle.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jsoup.helper.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.common.sysUtils.ExceptionUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.sysAssist.BatchService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.contract.service.ContractService;
import com.jy.modules.cims.creditright.service.CreditDealService;
import com.jy.modules.cims.data.common.dto.TCMmCooperorgDealDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmQuotaDTO;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.RedemptionCreditDetailDto;
import com.jy.modules.cims.deal.service.DealService;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.settle.service.CreditRedemptionService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.platform.restservice.web.base.BaseController;

/**
 * 结算处理控制层
 */
@Controller
@RequestMapping("/creditRedem")
public class CreditRedemptionController extends BaseController{
	
	
	private static final Logger logger = LoggerFactory.getLogger(CreditRedemptionController.class);
	
	private final String JSP_URL="cims/creditRedemption/";
    /**
     * 结算处理控制层
     */
    public CreditRedemptionController() {
    }
    @Autowired
    @Qualifier("com.jy.modules.cims.deal.service.DealService")
    public DealService dealService;
    @Autowired
    @Qualifier("com.jy.modules.cims.settle.service.CreditRedemptionService")
    public CreditRedemptionService creditRedemptionService;
    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
    private TCMmCooperorgDealService cooperorgDealService;
    @Autowired
    @Qualifier("com.jy.modules.cims.contract.service.ContractService")
    private ContractService serviceContract;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
    private ICInteract iCInteract;
    @Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	public IInteractAssist iInteractAssist;
    
    @Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.BatchService")
	public BatchService batchService;
    
    @Autowired
    @Qualifier("com.jy.modules.cims.creditright.service.CreditDealService")
    public CreditDealService creditDealService;
    
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName(JSP_URL+"queryCreditRedem");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
    		model.setViewName(JSP_URL+"addCreditRedem");
        }else if("toBackRedemptionAdd".equals(operate)){//跳转至贷款交易新增页面
        	String contractCode = this.getParameterString("contractCode");
        	model = serviceContract.queryAllDTO(contractCode);
        	model.setViewName(JSP_URL+"addCreditRedem");
        }else if("toBackRedemptionUpdate".equals(operate)){//跳转至债权交易修改页面
        	String contractCode = this.getParameterString("contractCode");
        	String dealCode = this.getParameterString("dealCode");
        	String cooperorgCode = this.getParameterString("cooperorgCode");
        	String id = this.getParameterString("id");
        	model = serviceContract.queryAllDTO(cooperorgCode,contractCode,dealCode);  
        	model.addObject("id", id);
        	model.setViewName(JSP_URL+"updateRedemption");
        }
        
        return model;
    }
    
    /**
     * 按明细赎回
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/operateExecute/{operate}")
    public ModelAndView doexecute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        if("toQuery".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/detailRedemption/queryTCMmCreditDetail");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	model.setViewName("cims/detailRedemption/viewTCMmCreditDetail");
        }
        return model;
    }

    /**
     * 结算处理
     * @param request 
     * @param response 
     * @return
     */
    public DataMsg settle(HttpServletRequest request, HttpServletResponse response) {
        // TODO implement here
        return null;
    }

    /**
     * 试算处理
     * @param request 
     * @param response 
     * @param result
     */
    public void trial(HttpServletRequest request, HttpServletResponse response, DataMsg result) {
        // TODO implement here
    }
    
    
    /**
     * @author JY-IT-D001
     * @description:通过主键查询 其明细信息
     * @date 2015-01-14 10:07:19
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmQuotaDTO dto=new TCMmQuotaDTO();
//        	TCMmQuotaDTO dto = service.queryTCMmQuotaByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    
    /**
     * 
     * @Title save
     * @Description 保存交易
     * @param request
     * @param response
     * @param result 
     * void 
     * @author lizhiqiang
     * @date 2015-1-20-上午9:45:29
     * @update 
     * @throws
     */
    @RequestMapping(value = "/testSettleCooperorgDeal")
    @ResponseBody
    public DataMsg testSettleCooperorgDeal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	 try {
         	 dto = (DealDto)super.initDto(dto);
//         	dealService.updateCreditDealDetailToCreditDetail(dto);
         	
             dataMsg = super.initDataMsg(dataMsg);
             dataMsg.setMsg("试算完成！");
             dataMsg.setData(this.makeJSONData(dto.getId()));
         }catch (Exception e) {
         	dataMsg.failed(e.getMessage());
         	logger.error("执行方法insertSysResource异常：", e);
         }
         return dataMsg;
    }
    
	/**
	 * 债权赎回交易流水查询
	 * @Title getDealCreditList
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2015-3-2-下午7:59:38
	 * @update 
	 * @throws
	 */
    @RequestMapping(value = "/getDealCreditRedemptionList")
    @ResponseBody
    public DataMsg getDealCreditRedemptionList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_REDEEM);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<DealDto> list = dealService.getDealList(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
	/**
	 * 贷款债权赎回交易流水查询
	 * @Title getDealCreditList
	 * @Description TODO
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2015-3-2-下午7:59:38
	 * @update 
	 * @throws
	 */
    @RequestMapping(value = "/getDealLoanCreditRedemptionList")
    @ResponseBody
    public DataMsg getDealLoanCreditRedemptionList(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setDealType(CimsConstant.DEAL_TYPE_LOAN_CREDIT_REDEEM);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<DealDto> list = dealService.getDealList(params.getSearchParams());
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
	
    /**
     * 根据债权包查询债权明细
     * @Title getCreditDetailRedemptionList
     * @Description TODO
     * @param request
     * @param dto
     * @param dataMsg
     * @return 
     * DataMsg 
     * @author lizhiqiang
     * @date 2015-3-3-上午11:42:40
     * @update 
     * @throws
     */
    @RequestMapping(value = "/getCreditDetailRedemptionList")
    @ResponseBody
    public DataMsg getCreditDetailRedemptionList(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) {
    	Date redeemDate = null;
    	String redemptionDate = (String)this.getParameter("redemptionDate");
    	if(!"".equals(redemptionDate)){
    		try {
    			redeemDate = DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);//可以选择赎回的债权
    	dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);//已转让
    	
    	dto.setTransferId(SimpleStringUtils.formatStringToSql(dto.getTransferId()));
    	dto.setCreditCode(SimpleStringUtils.formatStringToSql(dto.getCreditCode()));
    	
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<TCMmCreditDetailDTO> list = creditRedemptionService.getCreditDetailRedemptionList(params.getSearchParams());
//        String thisdate = DateTimeUtils.formatDate(new Date(), "yyyy-MM-dd");
//        if(list!=null&&list.size()>0&&!"".equals(redemptionDate)&&!thisdate.equals(redemptionDate)){
        if(list!=null&&list.size()>0&&!"".equals(redemptionDate)){
        	list = creditRedemptionService.getCreditDetailRedemptionListByInterface(list,redeemDate);
        }
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    /**
     * 债权明细赎回查询列表
     * @Title getCreditDetailListByRedempDetail
     * @Description TODO
     * @param request
     * @param dto
     * @param dataMsg
     * @return 
     * DataMsg 
     * @author lizhiqiang
     * @date 2016-6-7-上午10:38:30
     * @update 
     * @throws
     */
    @RequestMapping(value = "/getCreditDetailListByRedempDetail")
    @ResponseBody
    public DataMsg getCreditDetailListByRedempDetail(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) {
    	Date redeemDate = null;
    	String redemptionDate = (String)this.getParameter("redemptionDate");
    	if(!"".equals(redemptionDate)){
    		try {
    			redeemDate = DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}else{
    		//return dataMsg;
    	}
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);//可以选择赎回的债权
//    	dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);//已转让
    	
    	dto.setTransferId(SimpleStringUtils.formatStringToSql(dto.getTransferId()));
    	dto.setCreditCode(SimpleStringUtils.formatStringToSql(dto.getCreditCode()));
    	
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<CreditDetailDto> list = creditRedemptionService.getCreditDetailListByRedempDetail(params.getSearchParams());
        //接口取赎回日期的债权价值 
        if(list!=null&&list.size()>0&&!"".equals(redemptionDate)){
        	list = creditRedemptionService.getCreditDetailRedemptionList(list,redeemDate);
        }
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    
    
    
    /**
     * @author zhoupeng
     * @description:导出债权明细
     * @date 2015-10-31 16:21:37
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/exportCreditDetail")
    @ResponseBody
    public void exportCreditDetail(HttpServletRequest request,HttpServletResponse response, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	Date date = new Date();
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    	formatter.format(date);
		String dealDate = formatter.format(date);
		String fileName = "赎回明细"+dealDate;
    
		Date redeemDate = null;
    	String redemptionDate = (String)this.getParameter("redemptionDate");
    	if(!"".equals(redemptionDate)){
    		try {
    			redeemDate = DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	dto.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);//可以选择赎回的债权
//    	dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);//已转让
    	
    	dto.setTransferId(SimpleStringUtils.formatStringToSql(dto.getTransferId()));
    	dto.setCreditCode(SimpleStringUtils.formatStringToSql(dto.getCreditCode()));
    	
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
        List<CreditDetailDto> list = creditRedemptionService.getCreditDetailListByRedempDetailByExport(params.getSearchParams());
      //接口取赎回日期的债权价值 
        if(list!=null&&list.size()>0&&!"".equals(redemptionDate)){
        	list = creditRedemptionService.getCreditDetailRedemptionList(list,redeemDate);
        }
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        
    	ExportAndImport<CreditDetailDto> exportAndImport = new ExportAndImport<CreditDetailDto>();
    	String columnCode = CimsConstant.REDEMPTION_DETAIL_CODE;
    	String columnName = CimsConstant.REDEMPTION_DETAIL_NAME;
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.LOADDETAIL_FORM_FAILED + ":债权明细导出结果" + e);
		}
    }
    
    /**
  	 * 页面输出
  	 * @author zhoupeng
  	 * @param workbook
  	 * @param fileName
  	 * @param response
  	 * @throws IOException
  	 */
  	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

  		try {
  			
  			response.setContentType("application/vnd.ms-excel");
  			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
  			response.setCharacterEncoding("UTF-8");
  			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
  			workbook.write(response.getOutputStream());
  			response.getOutputStream().flush();
  		} catch (Exception e) {
  			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
  		} finally {
  			response.getOutputStream().close();
  		}
  	}
  	
    /**
     * 选择赎回的债权
     */
    @RequestMapping(value = "/updateCreditForRedemption")
    @ResponseBody
    public DataMsg updateCreditForRedemption(HttpServletRequest request, RedemptionCreditDetailDto dto, @ModelAttribute DataMsg dataMsg){
    	try {
	    	dto = (RedemptionCreditDetailDto)super.initDto(dto);
	    	String dealCode = dto.getDealCode();
	    	String did = this.getParameterString("id");
			Long dealId = !SimpleStringUtils.hasText(did)?null:Long.valueOf(did);
			Date dealDate = new Date();
	    	if(StringUtil.isBlank(dto.getDealCode())){
		    	// 创建交易流水信息
		    	DealDto dealDto = new DealDto();
	         	StringBuffer dealCodesb = new StringBuffer();
	         	creditRedemptionService.doGetDealCode(dealCodesb);
	         	dealCode = dealCodesb.toString();
	         	dealDto.setDealCode(dealCode);//交易流水号
	         	dealDto.setCooperativeAgencyDealStatus(CimsConstant.DEAL_STATUS_CREATE);//新建
	         	dealDto.setDealType(CimsConstant.DEAL_TYPE_CREDIT_REDEEM);
	         	dealDto.setContractCode(dto.getContractCode());
	         	dealDto.setCreditPackageName(dto.getPackageNum());
	         	dealDto.setRedemptionDate(dto.getRedeemDate());
	         	dealDto.setDealDate(dealDate);//交易日期
	         	dealDto.setCooperorgCode(dto.getCooperorgCode());
	         	dealDto.setAgreementCode(dto.getAgreementCode());
	         	dealId = cooperorgDealService.insertTCMmCooperorgDeal(dealDto);
	    	}
         	Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("id", dealId);
            resultMap.put("dealCode", dealCode);
            resultMap.put("dealDate", DateTimeUtils.formatDate(dealDate, "yyyy-MM-dd"));
         	//保存挑选结果
	    	TCMmCooperorgDealDTO dealdto = new TCMmCooperorgDealDTO();
	    	dealdto.setDealCode(dealCode);
	    	creditRedemptionService.saveCreditDealDetail(dto, dealdto);
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功！");
            dataMsg.setData(resultMap);
        }catch (Exception e) {
        	e.printStackTrace();
        	dataMsg.failed(e.getMessage());
        	dataMsg.setMsg(e.getMessage());
//        	 throw new SysAssistException(CimsExceptionConstant.ADD_CREDIT_FAILED + e.getMessage());
        }
        return dataMsg;
    }
    
    /**
     * @Title save
     * @Description 保存赎回交易
     * @param request
     * @param response
     * @param result 
     * void 
     * @author lizhiqiang
     * @date 2015-1-20-上午9:45:29
     * @update 
     * @throws
     */
    @RequestMapping(value = "/saveRedemptionDeal")
    @ResponseBody
    public DataMsg saveRedemptionDeal(HttpServletRequest request, DealDto dto, @ModelAttribute DataMsg dataMsg) {
    	 try {
    		// 保存交易
         	dto = (DealDto)super.initDto(dto);
         	
         	Map<String, Object> searchParams = new HashMap<String, Object>();
         	TCMmCooperorgDealDTO cooperorgDealDTO = new TCMmCooperorgDealDTO();
         	cooperorgDealDTO.setDealCode(dto.getDealCode());
         	searchParams.put("dto", cooperorgDealDTO);
         	cooperorgDealDTO = cooperorgDealService.searchTCMmCooperorgDeal(searchParams).get(0);
         	
         	dto.setCooperativeAgencyDealStatus(cooperorgDealDTO.getCooperativeAgencyDealStatus());
         	if(dto.getDealDate()==null){
         		dto.setDealDate(new Date());
         	}
         	
         	
         	cooperorgDealService.updateTCMmCooperorgDeal(dto);
             dataMsg = super.initDataMsg(dataMsg);
             dataMsg.setMsg("新增成功");
             dataMsg.setData(this.makeJSONData(dto.getId()));
         }catch (Exception e) {
         	dataMsg.failed(e.getMessage());
         	logger.error("执行方法insertSysResource异常：", e);
         }
         return dataMsg;
    }
    /**
     * 债权明细全部赎回
     * @Title redemptionAll
     * @Description TODO
     * @param request
     * @param dto
     * @param dataMsg
     * @return 
     * DataMsg 
     * @author lizhiqiang
     * @date 2016-6-12-上午10:33:58
     * @update 
     * @throws
     */
    @RequestMapping(value = "/redemptionAll")
    @ResponseBody
    public DataMsg redemptionAll(HttpServletRequest request, TCMmCreditDetailDTO dto, @ModelAttribute DataMsg dataMsg) {
    	try {
    		Date redeemDate = null;
        	String redemptionDate = (String)this.getParameter("redemptionDate");
        	if(!"".equals(redemptionDate)){
        		try {
        			redeemDate = DateTimeUtils.parseDate(redemptionDate, "yyyy-MM-dd");
        		} catch (Exception e) {
        			logger.error(ExceptionUtils.getStackTraceAsString(e));
        		}
        	}else{
        		return dataMsg;
        	}
        	Map<String, Object> searchParams = new HashMap<String, Object>();
        	dto.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);//可以选择赎回的债权
        	dto.setCreditorStatus(CimsConstant.CREDIT_STATUS_WIN);//已转让
        	
        	dto.setTransferId(SimpleStringUtils.formatStringToSql(dto.getTransferId()));
        	dto.setCreditCode(SimpleStringUtils.formatStringToSql(dto.getCreditCode()));
        	
        	searchParams.put("dto", dto);
            QueryReqBean params = new QueryReqBean();
            params.setSearchParams(searchParams);
        	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
    		params.setPageParameter(pageInfo);
            List<CreditDetailDto> list = creditRedemptionService.getCreditDetailListByRedempDetailByExport(params.getSearchParams());
            //接口取赎回日期的债权价值 
            if(list!=null&&list.size()>0&&!"".equals(redemptionDate)){
            	list = creditRedemptionService.getCreditDetailRedemptionList(list,redeemDate);
            }else{
            	throw new Exception("没有符合条件的债权！");
            }
            
            List<CreditDetailDto> loanlist = new ArrayList<CreditDetailDto>();
            List<CreditDetailDto> creditlist = new ArrayList<CreditDetailDto>();
            List<CreditDetailDto> redeemList = new ArrayList<CreditDetailDto>();
            for (CreditDetailDto creditDetailDto : list) {
				if(CimsConstant.CREDIT_SOURCE_LOA.equals(creditDetailDto.getCreditSource())){
					loanlist.add(creditDetailDto);
				}else if(CimsConstant.CREDIT_SOURCE_CRE.equals(creditDetailDto.getCreditSource())){
					creditlist.add(creditDetailDto);
				}else if(CimsConstant.CREDIT_SOURCE_REC.equals(creditDetailDto.getCreditSource())){
					redeemList.add(creditDetailDto);
				}
			}
            //1、赎回贷款明细
            if(loanlist.size()>0){
            	creditRedemptionService.doRedempCreditDetailByLoan(loanlist,redeemDate);
            	dataMsg.setMsg("贷款赎回成功！");
            }
            //2、赎回债权明细
            if(creditlist.size()>0){
            	creditRedemptionService.doRedempCreditDetailByCredit(creditlist,redeemDate);
            	if(dataMsg.getMsg()!=null){
            		dataMsg.setMsg(dataMsg.getMsg()+"债权赎回成功！");
            	}else{
            		dataMsg.setMsg("债权赎回成功！");
            	}
            }
            
            //2、赎回债权受让明细
            if(redeemList.size()>0){
    			// 批量确认受让赎回        	
            	creditRedemptionService.doTransfereeRedempDetailByCredit(redeemList,redeemDate);
            	if(dataMsg.getMsg()!=null){
            		dataMsg.setMsg(dataMsg.getMsg()+"受让赎回成功！");
            	}else{
            		dataMsg.setMsg("受让赎回成功！");
            	}
            }
            
            if(dataMsg.getMsg()==null)
            dataMsg.setMsg("没有符合条件的债权！");
            
            return dataMsg;
    	}catch (Exception e) {
    		dataMsg.failed(ExceptionUtils.getStackTraceAsString(e));
    		logger.error("执行方法insertSysResource异常：", e);
    	}
    	return dataMsg;
    }
    
    
	/**
	 * 删除赎回交易明细信息
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/deleteDetailByCredit")
	@ResponseBody
	public DataMsg deleteDetailByCredit(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		BaseDTO dto = super.initDto(null);
		String transferIds = (String) this.getParameter("transferIds");// 格式:
		String dealCode = (String) this.getParameter("dealCode");
		dataMsg = super.initDataMsg(dataMsg);
		try {
			creditRedemptionService.removeDetailByCredit(dto, transferIds,dealCode);
			dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);
		}

		return dataMsg;
	}
	
	/**
	 * 删除赎回交易
	 * 
	 * @param request
	 * @param response
	 * @param result
	 */
	@RequestMapping(value = "/deleteDeal")
	@ResponseBody
	public DataMsg deleteDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String ids = (String) this.getParameter("ids");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		String resultstr = null;
		try {
			resultstr = creditRedemptionService.doDeleteDeal(ids);
			dataMsg.setMsg(resultstr);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);
		}
		return dataMsg;
	}
	/**
	 * 发送结算申请
	 * @Title settleDeal
	 * @Description TODO
	 * @param request
	 * @param dataMsg
	 * @return 
	 * DataMsg 
	 * @author lizhiqiang
	 * @date 2016-4-18-上午10:28:37
	 * @update 
	 * @throws
	 */
	@RequestMapping(value = "/settleDeal")
	@ResponseBody
	public DataMsg settleDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String ids = (String) this.getParameter("ids");// 格式: 1,2,3
		dataMsg = super.initDataMsg(dataMsg);
		String resultstr = null;
		try {
			resultstr = creditRedemptionService.settleDeal(ids);
			dataMsg.setMsg(resultstr);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法settleDeal异常：", e);
		}
		return dataMsg;
	}
	
	/**
	 * 回滚赎回逻辑
	 */
	@RequestMapping(value = "/doNoRedemptionDeal")
	@ResponseBody
	public DataMsg doNoRedemptionDeal(HttpServletRequest request, @ModelAttribute DataMsg dataMsg) {
		String dealCode = (String) this.getParameter("dealCode");
		dataMsg = super.initDataMsg(dataMsg);
		String resultstr = null;
		try {
			resultstr = creditRedemptionService.doNoRedemptionDeal(dealCode);
			dataMsg.setMsg(resultstr);
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);
		}
		return dataMsg;
	}
	
	/**
	 * 赎回通知
	 * @author zhangmi
	 * @date  2017年1月18日
	 * @param request
	 * @param dto
	 * @param dataMsg
	 * @return
	 */
	@RequestMapping(value = "/doNoticeCredit")
	@ResponseBody
	public DataMsg doNoticeCreditRedemption(HttpServletRequest request,DealDto dto ,@ModelAttribute DataMsg dataMsg){
		dataMsg = super.initDataMsg(dataMsg);
		if(!SimpleStringUtils.hasText(dto.getDealCode())){
			dataMsg.setStatus("failed");
			dataMsg.failed("交易流水号不能为空！");
			return dataMsg;
		}
		try {
			String resultMsg = creditDealService.doSendCreditRedemption(dto);
			dataMsg.setMsg(resultMsg);
		} catch (Exception e) {
			dataMsg.failed(ExceptionUtils.getStackTraceAsString(e));
			logger.error("赎回通知异常：", ExceptionUtils.getStackTraceAsString(e));
		}
		return dataMsg;
	}
	
}